import { Component } from 'react';

import {Toast, Button , Group, Boxs, Context, Card, TextField, TextareaField, Badge, Dialog} from 'saltui';
const { IconButton } = Button;
const { HBox, Box, VBox } = Boxs;
import DB from '../../../app/db';
import SelectMember from 'components/selectMember';
import { msgNoData } from '../../../app/variables';
import Radio from 'components/radio';

import './PageHome.less';

export default class PageHome extends Component {

 constructor(props) {
    super(props);
    const now = new Date().getTime();
    let meetingId = this.props.params.id;
    if (meetingId == null || meetingId == '' || meetingId == undefined || meetingId == 'undefined') {
      meetingId = '';
    }
    var appropveTime = null;
    //关闭加载页的遮罩效果
    $(".loading-containter").hide();
    //禁用ios弹性事件
    dd.ui.webViewBounce.disable();
    scrollTo(0, 0);
    let type = this.props.params.type;
    let message = this.props.params.message;
    let attendWays = [
      { text:"现场参会", value:1 },
      { text:"网络参会", value:2 }
    ];
    this.state = {
      signedInfoId:'',
      id:'',
      meetingId:meetingId,
      memoId:'',
      name:'',
      startTime:'',
      endTime:'',
      address:'',
      meetingRoom:'',
      boardroomId: '',
      meetingAddress: '',
      meetingServer:'',
      meetingContent:'',
      createdName: '',
      appropveTime: appropveTime,

      joinDetails:'',
      emceeUser: '',
      memoUser: '',
      attendUser: '',

      isInitiator:'1',
      meetingRemain:'0',
      remainTime:'',
      remainType:'',
      meetingSign:'',
      signTime:'',
      signType: '',
      signRange: '',
      addressList: [],

      feedbackType:'0',
      status:'0',
      type:type,
      noticeStatus:'',

      activeIndex: 0,
      value3: now,
      iscanapprove:'0',
      signedDateTime:'',

      isTurnover:false,
      isMessage:message,
      isDeleted:false,
      needPostionSigned:false,
      needQrcodeSigned:false,

      inviter:null,

      attendWays:attendWays,
      attendWay:attendWays[0],
      meetingWay:0,
      reason:'',
      showDontAttendDialog:false,
      showAttendDialog:false,
      currentMeetingWay:0,
    };
    
    let t = this;
    let userId = document.getElementById("userHiddenId").value;
    var isHelpNew = 1;
    dd.util.domainStorage.getItem({ //帮助按钮
       name:'meeting_helpNew_'+userId , // 存储信息的key值
       onSuccess : function(info) {
            var helpNew = info.value;
            if( typeof(helpNew) == 'undefined' || helpNew == '' ){
              isHelpNew = 2;
            }
            //初始化按钮
            t.initButton(isHelpNew);
       },
       onFail : function(err) {
            //alert(JSON.stringify(err));
       }
    });

  }

  //初始化按钮
  initButton(isHelpNew){
    //设置帮助
    /*dd.biz.navigation.setIcon({
        showIcon : true,//是否显示icon
        iconIndex : isHelpNew,//显示的iconIndex,如上图
        onSuccess : function(result) {
            location.hash='help/help_index';
        },
        onFail : function(err) {
        //jsapi调用失败将会回调此函数
        }
    });*/
  }

  componentDidMount(){
    let mdtitle = '会议通知';
    var noticeType = "1";
    if(this.state.type == 'approve'){
      mdtitle = '审批';
      noticeType = "0";
    };
    $("title").text(mdtitle);
    var thirdMenuType = getLoginUserInfo().thirdMenuType;
    if(thirdMenuType == 'DING'){
      dd.biz.navigation.setTitle({
        title : mdtitle,//控制标题文本，空字符串表示显示默认文本
        onSuccess : function(result) {},
        onFail : function(err) {}
      });
    }else if(thirdMenuType =='MH'){
      !!emp&&emp.window.setTitle({
        title: {
            text: mdtitle,
            icon: '',
            actionmenu: {}
        },
      });
    }

    let t = this;
    let meetingId = t.state.meetingId;
    DB.SomeModuleAPI.attendNoticeInfo({id:meetingId, type:noticeType}).then((content) => {
      let isDeleted = content.isDeleted;
      if(t.state.isMessage == 'message' && isDeleted){
        t.setState({
          isDeleted:isDeleted
        })
        return false;
      }
      let applyRecord = content.applyRecord;
      let boardroomSet = content.boardroomSet;
      let meetingRoom = '';
      let boardroomId = '', meetingAddress = '';
      if (boardroomSet != null) {
        meetingRoom = boardroomSet.name;
        boardroomId = boardroomSet.id;
        meetingAddress = boardroomSet.address;
      }
      let meetingServer = '';
      if (content.serveSetCheckList != null) {
        for (var i=0; i<content.serveSetCheckList.length;i++) {
            if (meetingServer == '') {
                meetingServer= content.serveSetCheckList[i].text;
            } else {
              meetingServer=meetingServer + ',' + content.serveSetCheckList[i].text;
            }             
        }
      }

      let signedTime = "", signType = "";
      if(applyRecord.signedTime=="10"){
        signedTime = "开始前十分钟";
      }else if(applyRecord.signedTime=="30"){
        signedTime = "开始前半小时";
      }else if(applyRecord.signedTime=="60"){
        signedTime = "开始前一小时";
      }else if(applyRecord.signedTime=="0"){
        signedTime = "不限时";
      }

      if(applyRecord.signedType=="0"){
        signType = "扫码";
      }else if(applyRecord.signedType=="1"){
        signType = "定位";
      }else if(applyRecord.signedType=="2"){
        signType = "扫码+定位";
      }

      let iscanapprovelet = '0';
      let arStartTime = applyRecord.startTime;
      if(arStartTime.indexOf('-') >= 0){
        arStartTime = arStartTime.replace(/-/g, "/");
      }
      arStartTime = new Date(arStartTime).getTime();
      let nowDateTime =  new Date().getTime();
      if(arStartTime > nowDateTime){
        iscanapprovelet = '1';             
      }

      var noticeId = "";
      var _noticeStatus ="";
      var _inviter = null;
      if(content.noticeInfo!=null){
        noticeId = content.noticeInfo.id;
        _noticeStatus = content.noticeInfo.status;
        _inviter = content.noticeInfo.inviter;
      }

      t.setState({
        name:applyRecord.name,
        startTime:applyRecord.startTime,
        endTime:applyRecord.endTime,
        meetingRoom:meetingRoom,
        meetingAddress: meetingAddress,
        boardroomId:boardroomId,
        meetingServer:meetingServer,
        meetingContent:applyRecord.content,
        createdName: content.createdName,
        address: applyRecord.address,
        emceeUser:applyRecord.emceeUser,
        memoUser:applyRecord.memoUser,
        attendUser:applyRecord.attendUser,

        meetingRemain:applyRecord.isNotice,
        meetingSign:applyRecord.isSigned,
        signTime:signedTime,
        signTimeSelect:applyRecord.signedTime,
        signType: signType,
        signedType: applyRecord.signedType,
        signRange:applyRecord.signedRange,
        addressList:content.addressList,

        feedbackType:applyRecord.status,
        meetingWay:applyRecord.meetingWay,
        id:noticeId,
        noticeStatus:_noticeStatus,
        iscanapprove:iscanapprovelet,
        isTurnover:content.isTurnover,
        needPostionSigned:content.needPostionSigned,
        needQrcodeSigned:content.needQrcodeSigned,
        signedDateTime:content.signedDateTime,

        inviter:_inviter
      }, function(){
        t.refs.selectMember_emceeUser.initSelectData();
        t.refs.selectMember_memoUser.initSelectData();
        t.refs.selectMember_attendUser.initSelectData();
      });
             
    }).catch((error) => {

    });
  }

  onChange(val) {
    this.setState({
      value: val,
    });
  }

  // 同意
  agreeFuc(){
    let t = this;
    let param = {
      id:this.state.meetingId,
      noticeInfoId:this.state.id,
      status:'1'
    };

    DB.SomeModuleAPI.editApplyRecordInfo(param).then((content) => {

          Toast.show({
          type: 'success',
              content: '提交成功'
           });

          //返回至列表页面
          /*var appropveTime = t.state.appropveTime;
          if(appropveTime==null || appropveTime=="" || appropveTime==undefined){
            history.back();
          }else{
            setTimeout(function(){
              //history.back();
              backPage();
            },1000);
          }*/
          setTimeout(function(){
            //history.back();
            backPage();
          },1000);
        }).catch((error) => {
          
            if(typeof(error.errorMsg) == 'undefined'){
              Toast.show({
              type: 'error',
              content: '提交出错'
               });
            }else{
              Toast.show({
              type: 'error',
              content: error.errorMsg
               });
            }
        }); 
  }

  // 确认参会
  confirmJoin(){
    let t = this;
    let param = {id:this.state.id,status:'1'};
    DB.SomeModuleAPI.editNoticeInfo(param).then((content) => {
          Toast.show({
              type: 'success',
              content: '确认成功'
           });
          setTimeout(function(){
            //history.back();
            backPage();
          },1000);
        }).catch((error) => {
            if(typeof(error.errorMsg) == 'undefined'){
              Toast.show({
              type: 'error',
              content: '提交出错'
               });
            }else{
              Toast.show({
              type: 'error',
              content: error.errorMsg
               });
            }
        }); 
  }

  // 请假
  // leaveFuc(){
  //   location.hash = 'meeting/leaveReason/' + this.state.id;
  // }

  // turnover(){
  //   location.hash = 'meeting/turnover/' + this.state.id + '/' + this.state.meetingId;
  // }

  invitationClick(){
    location.hash = 'meeting/turnover/' + this.state.id + '/' + this.state.meetingId;
  }

  //不参会
  dontAttendClick(){
    this.setState({
      showDontAttendDialog: true,
    });
  }

  dontAttend(){
    let t = this;
    if (t.state.reason.trim() == '') {
      t.setState({
        showDontAttendDialog: false,
      },function(){
        setTimeout(function(){
          t.setState({
            showDontAttendDialog: true,
          })
        },1500);
        Toast.show({
          type: 'error',
          content: '请输入不参会原因',
        });
      })
      return false;
    }
    let param = {
      id: t.state.id,
      status: 3,
      reason: t.state.reason,
    };
    DB.SomeModuleAPI.editNoticeInfoStatus(param).then((content) => {
      if(content.code == -1){
        Toast.show({
          type: 'error',
          content: content.message,
        });
      }
      t.setState({
        showDontAttendDialog: false,
        reason:'',
        noticeStatus: 3
      });
    }).catch((error) => {
    });
  }

  //点击参会
  attendClick(meetingWay, noticeInfoId){
    let t = this;
    var  meetingWay1 = t.state.meetingWay;
    if(meetingWay1==0){
      meetingWay1=1;
    }else{
      meetingWay1=2;
    }
    Dialog.confirm({
      title: '提示',
      content: '确定参加会议？',
      onConfirm() {
        t.attendMeeting(meetingWay1);
        t.setState({
          showAttendDialog: false,
        });
      },
    });
    /**
    if(meetingWay == 2){
      t.setState({
        showAttendDialog: true,
      });
    }else{
      Dialog.confirm({
        title: '提示',
        content: '确定参加会议？',
        onConfirm() {
          t.attendMeeting(meetingWay1 == 0 ? 1 : 2);
          t.setState({
            showAttendDialog: false,
          });
        },
      });
      
    }
    **/
  }

  //参会
  attendMeeting(attendWay){
    let t = this;
    let param = {
      id: t.state.id,
      status: 2,
      attendWay: attendWay ? attendWay : t.state.meetingWay.value,
    };
    DB.SomeModuleAPI.editNoticeInfoStatus(param).then((content) => {
      if(content.code == -1){
        Toast.show({
          type: 'error',
          content: content.message,
        });
      }
      this.setState({
        showAttendDialog: false,
        noticeStatus: 2
      });
    }).catch((error) => {
    });
  }
  
  dialogChange(field, value){
    this.setState({
      [field]: value
    })
  }

  handleTextChange(field, newValue, size) {
    if (newValue.length <= size) {
      this.setState({
        [field]: newValue,
      });
    }
  }
  
  dialogCancle(){
    this.setState({
      showDontAttendDialog: false,
      showAttendDialog: false
    });
  }

  scanQrcode(){
    var thirdMenuType = getLoginUserInfo().thirdMenuType;
    let ipPort = getLoginUserInfo().contextPageUrl;
    //第三方标识：DING（钉钉），WX（企业微信），MH（移动门户）
    if(thirdMenuType=='DING'){
      dd.biz.util.scan({
        type: "qrCode" , // type 为 all、qrCode、barCode，默认是all。
        onSuccess: function(data) {
          pageSkipDirectly(ipPort + data.text);
        },
        onFail : function(err) {}
      })
    }else if(thirdMenuType=='WX'){
      wx.scanQRCode({
        desc: 'scanQRCode desc',
        needResult: 1, // 默认为0，扫描结果由企业微信处理，1则直接返回扫描结果，
        scanType: ["qrCode", "barCode"], // 可以指定扫二维码还是条形码（一维码），默认二者都有
        success: function(res) {
          pageSkipDirectly(ipPort + res.resultStr);
        },
        error: function(res) {
            if (res.errMsg.indexOf('function_not_exist') > 0) {
                alert('版本过低请升级')
            }
        }
      });
    }else if(thirdMenuType=='MH'){
      !!emp&&emp.scanQRCode({
        needResult: 1, // 默认为0，扫描结果由App处理，1则直接返回扫描结果，
        scanType: ["qrCode", "barCode"], // 可以指定扫二维码还是一维码，默认二者都有
        success: function (res) {
          pageSkipDirectly(ipPort + res.resultStr);
        }
      });
    }
  }

  //定位打卡
  positionSign(){
    let t = this;
    let nowDateTime = new Date().getTime();
    let signedDateTimelet = this.state.signedDateTime;
    if(signedDateTimelet.indexOf('-') >= 0){
      var reg = new RegExp("-","g");
      signedDateTimelet = signedDateTimelet.replace(reg,"/");
    }
    signedDateTimelet = new Date(signedDateTimelet).getTime();
    if(t.state.signTimeSelect!="0" && nowDateTime < signedDateTimelet){
      Toast.show({
        type: 'error',
        content: '未到签到时间',
        onHide: function () {
        }
      });
      return;
    }else{
      DB.SomeModuleAPI.entityIsExist({id:t.state.meetingId}).then((content) => {
        if(content == 'notExist'){
          Toast.show({
            type: 'error',
            content: '当前数据已删除',
          });
          history.back();
        }else{
          location.hash = 'meeting/positionSign/' + t.state.meetingId;
        }
      }).catch((error) => {
      });
    }
  }

  //获取联系人
  getHosterPersion(newValue){
      this.setState({hoster:newValue});
  }

  getMemoerPersion(newValue){
      this.setState({memoer:newValue});
  }

  getJoinPersion(newValue){
      this.setState({joiners:newValue});
  }

  render() {
    const t = this;
    let isDeleted = t.state.isDeleted;
    if(!isDeleted){
      const headerCls = Context.prefixClass('card-header');
      var meetingAddress = ""
      if(this.state.boardroomId!="" && this.state.meetingRoom != ""){
        meetingAddress = this.state.meetingRoom+"（"+this.state.meetingAddress+"）";
      }else{
        meetingAddress = this.state.address;
      }

      var addressHtml = "";
      var addressList = this.state.addressList;
      if(addressList!=null && addressList.length>0){
        addressHtml = addressList.map((item, index) => {
          return (
            <div className="dd-t-list-wrap">
              <HBox vAlign="center">
                <Box className="t-list-text-content" flex={1}>
                  <VBox vAlign="center" className="t-list-text t-FBJ">
                    <Box>{item.address}</Box>
                  </VBox>
                </Box>
              </HBox>
            </div>
          );
        });
      }
      let noticeStatus = t.state.noticeStatus;
      return (
        <div className="meeting-details t-PB68">
          <div className="card-wrap">
            <Card className="card-sence">
              <div className={headerCls + ' t-P0'}>
                <div className="card-username"> {t.state.name}</div>
                <Badge className={this.state.feedbackType==3?'':'t-DN'} text={'已取消'} style={{left: 10, background: '#ddd', }}/>
                <Badge className={this.state.feedbackType==2?'':'t-DN'} text={'已驳回'} style={{ left: 10, }}/>
                <Badge className={this.state.feedbackType==5?'':'t-DN'} text={'已结束'} style={{ left: 10, background: '#ccc', }}/>
                <Badge className={this.state.feedbackType==0?'':'t-DN'} text={'审批中'} style={{ left: 10, background: '#ff9933', }}/>
                <Badge className={this.state.feedbackType==4?'':'t-DN'} text={'进行中'} style={{ left: 10, background: '#66BC5C', }}/>
                <Badge className={this.state.feedbackType==1?'':'t-DN'} text={'未召开'} style={{ left: 10, background: '#8ccfec', }}/>
              </div>
              <div>
                <HBox>
                  <Box><i className="iconfont icon-manager t-FCc t-MR4 t-LH1_6" style={{fontSize:14}}></i></Box>
                  <Box className="card-desc">发起人：</Box>
                  <Box flex={1} className="card-desc">{t.state.createdName}</Box>
                </HBox>
                <HBox>
                  <Box><i className="iconfont icon-time t-FCc t-MR4 t-LH1_6" style={{fontSize:14}}></i></Box>
                  <Box className="card-desc">开始时间：</Box>
                  <Box flex={1} className="card-desc">{t.state.startTime}</Box>
                </HBox>
                <HBox>
                  <Box><i className="iconfont icon-time t-FCc t-MR4 t-LH1_6" style={{fontSize:14}}></i></Box>
                  <Box className="card-desc">结束时间：</Box>
                  <Box flex={1} className="card-desc">{t.state.endTime}</Box>
                </HBox>
                <HBox>
                  <Box><i className="iconfont icon-place t-FCc t-MR4 t-LH1_6" style={{fontSize:14}}></i></Box>
                  <Box className="card-desc">会议地址：</Box>
                  <Box flex={1} className="card-desc">{meetingAddress=="" ? "无" : meetingAddress}</Box>
                </HBox>
                {this.state.boardroomId == "" ? "" : 
                <HBox>
                  <Box><i className="iconfont icon-service t-FCc t-MR4 t-LH1_6" style={{fontSize:14}}></i></Box>
                  <Box className="card-desc">会议服务：</Box>
                  <Box flex={1} className="card-desc">{t.state.meetingServer}</Box>
                </HBox>
                }
                <div className="t-LH1_8 t-PT8">
                    <div
                      dangerouslySetInnerHTML={{
                          __html: t.state.meetingContent
                      }}>
                  </div>
                </div>    
              </div>
            </Card>            
            <Group.List>
              <SelectMember
                required={false}
                readOnly={true}
                label="主持人"
                placeholder="请选择成员对象"
                code="user"
                checkType="radio"
                fieldDataValue={t.state.emceeUser}
                scopeTable="oa_meeting_apply_record_scope"
                fieldTable="oa_meeting_apply_record"
                fieldData="emcee_user"
                ref="selectMember_emceeUser"
                isDelete={false}
                showType="list"
                includeDel="1"
              />
            </Group.List>

            <Group.List>
              <SelectMember
                required={false}
                readOnly={true}
                label="记录人"
                placeholder="请选择成员对象"
                code="user"
                checkType="radio"
                fieldDataValue={t.state.memoUser}
                scopeTable="oa_meeting_apply_record_scope"
                fieldTable="oa_meeting_apply_record"
                fieldData="memo_user"
                ref="selectMember_memoUser"
                isDelete={false}
                showType="list"
                includeDel="1"
              />
            </Group.List>
            <Group.List>
              <SelectMember
                required={false}
                readOnly={true}
                label="参会人员"
                placeholder="请选择成员对象"
                code="user,org"
                checkType="checkbox"
                fieldDataValue={t.state.attendUser}
                scopeTable="oa_meeting_apply_record_scope"
                fieldTable="oa_meeting_apply_record"
                fieldData="attend_user"
                ref="selectMember_attendUser"
                isDelete={false}
                showType="list"
                includeDel="1"
              />
            </Group.List>
            <Group.List>
          <SelectMember
            required={false}
            readOnly={true}
            label="会议列席人"
            placeholder="请选择会议列席人"
            code="user,org,station,group"
            chooseType="userAndGroup,userAndOrg,personalGroup"
            checkType="checkbox"
            fieldDataValue={t.state.attendants}
            scopeTable="oa_meeting_apply_record_scope"
            fieldTable="oa_meeting_apply_record"
            fieldData="meeting_attendants"
            ref="selectMember_attendants"
            isDelete={false}
            showType="list"
            includeDel="1"
          />
        </Group.List>

            <div className={this.state.type != 'approve' ? '' :'t-DN'}>
              <div className={this.state.meetingSign == '1' ? '' : 't-DN'}>
                <Group.List >
                  <TextField readOnly={true} label="签到方式" value={this.state.signType}/>
                </Group.List>
                <Group.List className={t.state.signedType=="1"||t.state.signedType=="2" ? '' : 't-DN'}>
                  <TextField readOnly={true} label="有效范围" value={this.state.signRange + "米"}/>
                </Group.List>
                { addressHtml }
                <Group.List >
                  <TextField readOnly={true} label="签到时间" value={this.state.signTime}/>
                </Group.List>
              </div>
            </div>
          </div>
          
          <div className={t.state.type == 'notice' ? '' :'t-DN'}>
            {/* <div className={(this.state.feedbackType==1 && noticeStatus != "4") ? '' : 't-DN'}>
              <Button.Group>
                <Button type="primary" display="inline" className={t.state.needPostionSigned ?'':'t-DN'} onClick={this.positionSign.bind(this)}>定位签到</Button>
                <Button type="primary" display="inline" className={noticeStatus == "2" ? 't-DN':''} onClick={this.confirmJoin.bind(this)}>确认参会</Button>
                <Button type="secondary" display="inline" className={noticeStatus == "3" ? 't-DN':''} onClick={this.leaveFuc.bind(this)}>请假</Button>
                <Button type="secondary" display="inline" className={noticeStatus == "5" || t.state.isTurnover ? 't-DN':''} onClick={this.turnover.bind(this)}>转本部门</Button>          
              </Button.Group>
            </div> */}

            <div className={this.state.feedbackType==1  ? '' : 't-DN'}>
              <Button.Group>
                <Button className={t.state.needPostionSigned ?'':'t-DN'} type="primary" display="inline" onClick={this.positionSign.bind(this)}>定位签到</Button>
                <Button className={t.state.noticeStatus !=9 && t.state.inviter == null ? "":"t-DN"} type="secondary" display="inline" onClick={this.invitationClick.bind(this)}>邀请</Button>
                <Button className={t.state.noticeStatus !=3 ? "":"t-DN"} type="secondary" display="inline" onClick={this.dontAttendClick.bind(this)}>不参会</Button>
                <Button className={t.state.noticeStatus !=2 ? "":"t-DN"} type="primary" display="inline" onClick={this.attendClick.bind(this)}>参会</Button>
              </Button.Group>
            </div>
          </div>
          <IconButton className={(this.state.feedbackType==1 && t.state.needQrcodeSigned) ? 'add-new-page t-BCddblue' : 't-DN'}onClick={this.scanQrcode.bind(this)} ><i className="iconfont icon-scan t-FCf"></i></IconButton>            
        
          <Dialog
            key="dontAttend-confirm"
            title="提示"
            show={this.state.showDontAttendDialog}
            type="confirm"
            onConfirm={() => { t.dontAttend(); }}
            onCancel={() => { t.dialogCancle(); }}
          >
            <Group.List >
              <TextareaField
                  layout="v"
                  placeholder="请输入不参会原因"
                  value={this.state.reason}
                  onChange={(value) => { t.handleTextChange('reason', value, 20); }}
              />
            </Group.List>
          </Dialog>

          <Dialog
            key="attend-confirm"
            title="请选择参会方式"
            show={this.state.showAttendDialog}
            type="confirm"
            onConfirm={() => { t.attendMeeting(); }}
            onCancel={() => { t.dialogCancle(); }}
          >
            <Radio
              data={t.state.attendWays}
              value={t.state.attendWay}
              onChange={(value)=>{ t.dialogChange('attendWay', value);}}
            ></Radio>
          </Dialog>
        </div>)
    }else{
      return (
        <div className="dd-state-page">
          <div className="dd-state-box">
            <VBox hAlign="center">
              <Box>
                <div>
                  <img src={msgNoData} alt="" />
                </div>
              </Box>
              <Box className="t-FS14 t-MT30 t-FAC t-LH1_3 t-FCddfontblue-40">
                内容已删除
              </Box>
            </VBox>
          </div>
        </div>
      )
    }
  }
}


